//
//  XDInputView.m
//  XDHoHo
//
//  Created by xieyajie on 20-11-25.
//  Copyright (c) 2013年 XD. All rights reserved.
//

#import "XDInputView.h"

#import "UIImage+Category.h"
//#import "XDCategory.h"
//#import "XDKeyboard.h"

#define DEFAULT_HEIGHT_INIT 44.0
#define DEFAULT_HEIGHT_MAX  120.0
#define DEFAULT_FONT        [UIFont systemFontOfSize:14.0]

@interface XDInputView ()
{
//    XDKeyboard *_keyboard;
    
    UIView *_containerView;
    UIImageView *_bgImageView;
    UILabel *_placeholderLabel;
    
    UIView *_tempRightOuterView;
    
    CGSize _textSize;
    BOOL _isInputting;
    BOOL _enableResize;
    BOOL _showCancelButton;
}

@property (nonatomic, weak) UIView *superView;
@property (nonatomic, weak) UIView *topView;
@property (nonatomic, strong) UIButton *cancelButton;

@end

@implementation XDInputView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, DEFAULT_HEIGHT_INIT)];
    if (self) {
        _style = XDInputViewStyleDefault;
        
        _enableCustomKeyboard   = NO;
        _enableFaceKeyboard     = NO;
        _enableResize           = NO;
        _showCancelButton       = NO;
        _hideWhenResign         = NO;
        _resignWhenReturn       = YES;
        
        //容器视图
        _containerView = [[UIView alloc] initWithFrame:self.bounds];
        _containerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        _containerView.backgroundColor = [UIColor clearColor];
        [self addSubview:_containerView];
        
        //背景
        _bgImageView = [[UIImageView alloc] initWithFrame:_containerView.bounds];
        _bgImageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [_containerView addSubview:_bgImageView];
        
        //主视图
        _centerView = [[UIView alloc] initWithFrame:CGRectMake(5.0, 7.0, self.bounds.size.width - 10.0, 32.0)];
        _centerView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        [_containerView addSubview:_centerView];
        
        //输入框背景
        _textBGImageView = [[UIImageView alloc] initWithFrame:_centerView.bounds];
        _textBGImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        [_centerView addSubview:_textBGImageView];
        
        //输入框
        CGRect frame = _textBGImageView.frame;
        frame.size.width -= 2.0;
        frame.size.height -= 2.0;
        _textView = [[UITextView alloc] initWithFrame:frame];
        _textView.delegate = self;
        _textView.scrollEnabled = NO;
        _textView.enablesReturnKeyAutomatically = YES;
        _textView.returnKeyType = UIReturnKeySearch;
        _textView.backgroundColor = [UIColor clearColor];
        _textView.font = DEFAULT_FONT;
        _textView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        
        [_centerView addSubview:_textView];
    }
    return self;
}

- (id)initWithSuperView:(UIView *)superView topView:(UIView *)topView
{
    self = [self initWithFrame:CGRectMake(0.0, superView.frame.size.height - DEFAULT_HEIGHT_INIT, superView.frame.size.width, DEFAULT_HEIGHT_INIT)];
    if (self) {
        if (superView) {
            [superView addSubview:self];
            _superView = superView;
        }
        
        if (topView) {
            CGRect frame = topView.frame;
            frame.size.height = superView.frame.size.height - frame.origin.y - (_hideWhenResign ? 0.0 : DEFAULT_HEIGHT_INIT);
            topView.frame = frame;
            _topView = topView;
        }
    }
    return self;
}

- (id)initWithSuperView:(UIView *)superView
{
    return [self initWithSuperView:superView topView:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



#pragma mark - View

- (void)layoutSubviews
{    
    if (!_bgImageView.image) {
        _bgImageView.image = self.backgroundImage;
    }
    
    if (!_textBGImageView.image) {
        _textBGImageView.image = self.textBackgroundImage;
    }
    
    _placeholderLabel.hidden = _textView.text.length;// (_textView.isFirstResponder || _textView.text.length);
    
    if (_enableResize) {
        _textSize = [_textView.text sizeWithFont:DEFAULT_FONT constrainedToSize:CGSizeMake(_textView.frame.size.width - 16.0, DEFAULT_HEIGHT_MAX - 10.0)];
        
        float off = 0.0;
        float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
        if (systemVersion >= 7.0) {
            off = 5.0;
        }
        //收起时高度一起改变
        if (!_textView.isFirstResponder) {
            CGRect frame = self.frame;
            frame.size.height = MAX(_textSize.height + 16.0 + 10.0 + off, 44.0);
            frame.origin.y = _hideWhenResign ? _superView.frame.size.height : _superView.frame.size.height - frame.size.height;
            self.frame = frame;
        }
        
        [UIView animateWithDuration:0.1 animations:^{
            CGRect frame = _containerView.frame;
            frame.size.height = MAX(_textSize.height + 16.0 + 10.0 + off, 44.0);
            frame.origin.y = self.bounds.size.height - frame.size.height;
            _containerView.frame = frame;
            _containerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        }];
        
        [self refreshFrame];
    } else {
        _textSize = [_textView.text sizeWithFont:DEFAULT_FONT constrainedToSize:CGSizeMake(_textView.frame.size.width - 16.0, DEFAULT_HEIGHT_INIT - 10.0)];
    }
    
    _textView.scrollEnabled = (_textView.contentSize.height > _textSize.height + 16.0 && _textView.contentSize.height > DEFAULT_HEIGHT_INIT);
}

- (void)refresh
{
    [self setNeedsLayout];
}

- (void)refreshFrame
{
    if (_topView) {
        [UIView animateWithDuration:0.35 animations:^{
            CGRect tempFrame = _topView.frame;
            if (_textView.isFirstResponder) {
                tempFrame.size.height = self.frame.size.height - tempFrame.origin.y - _containerView.frame.size.height;
            } else {
                tempFrame.size.height = _superView.frame.size.height - tempFrame.origin.y - (_hideWhenResign ? 0.0 : _containerView.frame.size.height);
            }
            _topView.frame = tempFrame;
        }];
    }
    
    if ([_delegate respondsToSelector:@selector(inputViewDidChangeFrame:)]) {
        [_delegate inputViewDidChangeFrame:self];
    }
}

- (void)setupCenterView
{
    CGFloat leftWidth = _leftOuterView ? _leftOuterView.frame.size.width + 10.0 : 5.0;
    CGFloat rightWidth = _rightOuterView ? _rightOuterView.frame.size.width + 10.0 : 5.0;
    CGRect frame = _centerView.frame;
    frame.origin.x = leftWidth;
    frame.size.width = _containerView.bounds.size.width - leftWidth - rightWidth;
    _centerView.frame = frame;
    _centerView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
}

- (void)setupTextView
{
    CGFloat leftWidth = _leftInnerView ? _leftInnerView.frame.size.width - 6.0 : 0.0;
    CGFloat rightWidth = _rightInnerView ? _rightInnerView.frame.size.width - 4.0 : 2.0;
    CGRect frame = _textView.frame;
    frame.origin.x = leftWidth;
    frame.size.width = _centerView.bounds.size.width - leftWidth - rightWidth;
    _textView.frame = frame;
    _textView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    frame.origin.x += 8.0;
    frame.size.width -= 16.0;
    _placeholderLabel.frame = frame;
    _placeholderLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
}



#pragma mark - UIResponder Delegate

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_textView resignFirstResponder];
}

- (BOOL)isFirstResponder
{
    return [_textView isFirstResponder];
}

- (BOOL)becomeFirstResponder
{
    return [_textView becomeFirstResponder];
}

- (BOOL)resignFirstResponder
{
    return [_textView resignFirstResponder];
}



#pragma mark - Properties

- (void)setStyle:(XDInputViewStyle)style
{
    if (style == XDInputViewStyleDefault) {
        _enableResize = NO;
        _textView.returnKeyType = UIReturnKeySearch;
        
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    } else if (style == XDInputViewStyleBottom) {
        _enableResize = YES;
        _textView.returnKeyType = UIReturnKeyNext;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    
    _style = style;
    
    [self refresh];
}

//- (void)setEnableCustomKeyboard:(BOOL)enableCustomKeyboard
//{
//    _enableCustomKeyboard = enableCustomKeyboard;
//    
//    if (enableCustomKeyboard && !_keyboard) {
//        _keyboard = [[XDKeyboard alloc] initWithTextView:_textView];
//    }
//}
//
//- (void)setEnableFaceKeyboard:(BOOL)enableFaceKeyboard
//{
//    _enableFaceKeyboard = enableFaceKeyboard;
//    
//    if (enableFaceKeyboard) {
//        if (!_faceKeyboard) {
//            _faceKeyboard = [[XDFaceKeyboard alloc] initWithTextView:_textView];
//            _faceKeyboard.delegate = self;
//        }
//        if (!_faceButton) {
//            _faceButton = [[XDButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 30.0, 30.0)
//                                                      image:[UIImage imageNamed:@"chat_toolbar_smiley"]
//                                                     target:self
//                                                     action:@selector(switchKeyboard)];
//        }
//        if (!_rightOuterView) {
//            self.rightOuterView = _faceButton;
//        }
//    } else {
//        _faceKeyboard = nil;
//        
//        if (_faceButton.tag == 1) {//显示表情键盘
//            _textView.inputView = nil;
//            [_textView reloadInputViews];
//        }
//
//        [_faceButton removeFromSuperview];
//        _faceButton = nil;
//    }
//}

- (UIImage *)backgroundImage
{
    if (!_backgroundImage) {
        if (_style == XDInputViewStyleDefault) {
            _backgroundImage = [[UIImage imageNamed:@"search_bg"] resizableImageWithCompatibleCapInsets:UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0) resizingMode:UIImageResizingModeTile];
        } else if (_style == XDInputViewStyleBottom) {
            _backgroundImage = [[UIImage imageNamed:@"area_bg"] resizableImageWithCompatibleCapInsets:UIEdgeInsetsMake(2.0, 0.0, 40.0, 0.0) resizingMode:UIImageResizingModeStretch];
        }
    }
    return _backgroundImage;
}

- (void)setBackgroundImage:(UIImage *)backgroundImage
{
    _backgroundImage = backgroundImage;
    _bgImageView.image = backgroundImage;
}

- (UIImage *)textBackgroundImage
{
    if (!_textBackgroundImage) {
        if (_style == XDInputViewStyleDefault) {
            _textBackgroundImage = [[UIImage imageNamed:@"input_text_bg"] resizableImageWithCompatibleCapInsets:UIEdgeInsetsMake(0.0, 15.0, 0.0, 15.0) resizingMode:UIImageResizingModeStretch];
        } else if (_style == XDInputViewStyleBottom) {
            _textBackgroundImage = [[UIImage imageNamed:@"area_input_bg"] resizableImageWithCompatibleCapInsets:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0) resizingMode:UIImageResizingModeStretch];
        }
    }
    return _textBackgroundImage;
}

- (void)setTextBackgroundImage:(UIImage *)textBackgroundImage
{
    _textBackgroundImage = textBackgroundImage;
    _textBGImageView.image = textBackgroundImage;
}

- (void)setLeftInnerView:(UIView *)leftInnerView
{
    [_leftInnerView removeFromSuperview];
    _leftInnerView = leftInnerView;
    
    CGRect frame = _leftInnerView.frame;
    frame.size.width = MIN(frame.size.width, 30.0);
    frame.size.height = MIN(frame.size.height, 30.0);
    _leftInnerView.frame = frame;
    _leftInnerView.center = CGPointMake(frame.size.width / 2.0 + 2.0, _centerView.frame.size.height - 17.0);
    _leftInnerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleRightMargin;
    [_centerView addSubview:_leftInnerView];
    
    [self setupTextView];
}

- (void)setRightInnerView:(UIView *)rightInnerView
{
    [_rightInnerView removeFromSuperview];
    _rightInnerView = rightInnerView;
    
    CGRect frame = _rightInnerView.frame;
    frame.size.width = MIN(frame.size.width, 30.0);
    frame.size.height = MIN(frame.size.height, 30.0);
    _rightInnerView.frame = frame;
    _rightInnerView.center = CGPointMake(_centerView.frame.size.width - frame.size.width / 2.0 - 2.0, _centerView.frame.size.height - 17.0);
    _rightInnerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin;
    [_centerView addSubview:_rightInnerView];
    
    [self setupTextView];
}

- (void)setLeftOuterView:(UIView *)leftOuterView
{
    [_leftOuterView removeFromSuperview];
    _leftOuterView = leftOuterView;
    
    CGRect frame = _leftOuterView.frame;
    frame.size.width = MIN(frame.size.width, 100.0);
    frame.size.height = MIN(frame.size.height, 30.0);
    _leftOuterView.frame = frame;
    _leftOuterView.center = CGPointMake(frame.size.width / 2.0 + 5.0, _containerView.frame.size.height - 22.0);
    _leftOuterView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [_containerView addSubview:_leftOuterView];
    
    [self setupCenterView];
}

- (void)setRightOuterView:(UIView *)rightOuterView
{
    [_rightOuterView removeFromSuperview];
    _rightOuterView = rightOuterView;
    
    CGRect frame = _rightOuterView.frame;
    frame.size.width = MIN(frame.size.width, 100.0);
    frame.size.height = MIN(frame.size.height, 30.0);
    _rightOuterView.frame = frame;
    _rightOuterView.center = CGPointMake(_containerView.frame.size.width - frame.size.width / 2.0 - 5.0, _containerView.frame.size.height - 22.0);
    _rightOuterView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [_containerView addSubview:_rightOuterView];
    
    [self setupCenterView];
}

- (NSString *)text
{
    return _textView.text;
}

- (void)setText:(NSString *)text
{
    _textView.text = text;
    [self refresh];
}

- (NSString *)placeholder
{
    return _placeholderLabel.text;
}

- (void)setPlaceholder:(NSString *)placeholder
{
    if (!_placeholderLabel) {
        CGRect frame = _textView.frame;
        frame.origin.x += 8.0;
        frame.size.width -= 16.0;
        _placeholderLabel = [[UILabel alloc] initWithFrame:frame];
        _placeholderLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _placeholderLabel.hidden = YES;
        _placeholderLabel.backgroundColor = [UIColor clearColor];
        _placeholderLabel.font = _textView.font;
        _placeholderLabel.textColor = [UIColor lightGrayColor];
        [_centerView insertSubview:_placeholderLabel belowSubview:_textView];
    }
    _placeholderLabel.text = placeholder;
    [self refresh];
}

- (UIButton *)cancelButton
{
    if (!_cancelButton) {
        UIImage *bgImage = [[UIImage imageNamed:@"navi_item"] resizableImageWithCompatibleCapInsets:UIEdgeInsetsMake(5.0, 5.0, 5.0, 5.0) resizingMode:UIImageResizingModeStretch];
        _cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 50.0, 30.0)];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton setBackgroundImage:bgImage forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(hideCancelButton) forControlEvents:UIControlEventTouchUpInside];
        [_cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
    }
    return _cancelButton;
}



#pragma mark - TextView Delegate

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    _isInputting = YES;
    [self refresh];
    
    //取消按钮
    if (_style == XDInputViewStyleDefault) {
        [self showCancelButton:YES];
    }
    
    if ([_delegate respondsToSelector:@selector(inputViewShouldBeginEditing:)]) {
        return [_delegate inputViewShouldBeginEditing:self];
    }
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
//    if (_faceButton.tag == 1) {//恢复文本输入键盘
//        _faceButton.tag = 0;
//        [_faceButton setImage:[UIImage imageNamed:@"chat_toolbar_smiley"] forState:UIControlStateNormal];
//        
//        _textView.inputView = nil;
//    }
    
    if ([_delegate respondsToSelector:@selector(inputViewShouldEndEditing:)]) {
        return [_delegate inputViewShouldEndEditing:self];
    }
    return YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([_delegate respondsToSelector:@selector(inputViewDidBeginEditing:)]) {
        [_delegate inputViewDidBeginEditing:self];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    _isInputting = NO;
    [self refresh];
    
    if ([_delegate respondsToSelector:@selector(inputViewDidEndEditing:)]) {
        [_delegate inputViewDidEndEditing:self];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        if (textView.returnKeyType != UIReturnKeyNext) {
            if ([_delegate respondsToSelector:@selector(inputViewReturnButtonClicked:)]) {
                [_delegate inputViewReturnButtonClicked:self];
            }
            
            if (_resignWhenReturn) {
                [textView resignFirstResponder];//回调完成后再更改状态
            }
            return NO;
        }
    }
    
    if ([_delegate respondsToSelector:@selector(inputView:shouldChangeTextInRange:replacementText:)]) {
        return [_delegate inputView:self shouldChangeTextInRange:range replacementText:text];
    }
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    [self refresh];
    
    if ([_delegate respondsToSelector:@selector(inputViewDidChange:)]) {
        [_delegate inputViewDidChange:self];
    }
}

- (void)textViewDidChangeSelection:(UITextView *)textView
{
    if ([_delegate respondsToSelector:@selector(inputViewDidChangeSelection:)]) {
        [_delegate inputViewDidChangeSelection:self];
    }
}



#pragma mark - XDFaceKeyboard Delegate

//- (void)faceKeyboardSendButtonClicked:(XDFaceKeyboard *)keyboard
//{
//    if ([_delegate respondsToSelector:@selector(inputViewReturnButtonClicked:)]) {
//        [_delegate inputViewReturnButtonClicked:self];
//    }
//    
//    if (_resignWhenReturn) {
//        if (_textView.text.length) {//有文本时收起表情键盘
//            [_textView resignFirstResponder];//回调完成后再更改状态
//        }
//    }
//}
//
//- (void)faceKeyboard:(XDFaceKeyboard *)keyboard didInputFaceMedia:(NSData *)faceMedia
//{
//    if ([_delegate respondsToSelector:@selector(inputView:didInputMediaWithInfo:)]) {
//        NSDictionary *info = faceMedia ? @{@"media": faceMedia} : nil;
//        [_delegate inputView:self didInputMediaWithInfo:info];
//    }
//}
//
//- (void)faceKeyboard:(XDFaceKeyboard *)keyboard didInputFacePath:(NSString *)facePath
//{
//    if ([_delegate respondsToSelector:@selector(inputView:didInputMediaWithInfo:)]) {
//        NSDictionary *info = facePath.length ? @{@"path": facePath} : nil;
//        [_delegate inputView:self didInputMediaWithInfo:info];
//    }
//}



#pragma mark - Input State

/*隐藏取消搜索*/
- (void)hideCancelButton
{
    [self showCancelButton:NO];
}

/*显示/隐藏取消按钮*/
- (void)showCancelButton:(BOOL)showCancelButton
{
    _showCancelButton = showCancelButton;
    
    if (showCancelButton) {
        if (!_tempRightOuterView) {
            _tempRightOuterView = _rightOuterView != self.cancelButton ? _rightOuterView : nil;
        }
        self.rightOuterView = self.cancelButton;
    } else {
        self.rightOuterView = _tempRightOuterView;
        _tempRightOuterView = nil;
        
        if ([_delegate respondsToSelector:@selector(inputViewCancelButtonClicked:)]) {
            [_delegate inputViewCancelButtonClicked:self];
        }
        [self resignFirstResponder];
    }
}

/*切换文本键盘和表情键盘*/
//- (void)switchKeyboard
//{
//    _faceButton.tag = !_faceButton.tag;
//    
//    UIImage *image = (_faceButton.tag == 0) ? [UIImage imageNamed:@"chat_toolbar_smiley"] : [UIImage imageNamed:@"chat_toolbar_text"];
//    [_faceButton setImage:image forState:UIControlStateNormal];
//    
//    _textView.inputView = (_faceButton.tag == 1) ? _faceKeyboard : nil;
//    if ([_textView isFirstResponder]) {
//        [_textView reloadInputViews];
//    } else {
//        [_textView becomeFirstResponder];
//    }
//}



#pragma mark - UIKeyboard Notification

- (void)keyboardWillShow:(NSNotification *)notification
{
    CGRect keyboardRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval animationDuration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:animationDuration animations:^{
        CGRect frame = self.frame;
        frame.origin.y = 0.0;
        frame.size.height = _superView.frame.size.height - keyboardRect.size.height;
        self.frame = frame;
    }];
    
    [self refresh];
    [self refreshFrame];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    NSTimeInterval animationDuration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:animationDuration animations:^{
        CGRect frame = self.frame;
        
//        frame.origin.y = _superView.frame.size.height - DEFAULT_HEIGHT_INIT;
//        frame.size.height = DEFAULT_HEIGHT_INIT;
        
        //收起时不恢复初始高度
        frame.size.height = _containerView.frame.size.height;
        frame.origin.y = _hideWhenResign ? _superView.frame.size.height : _superView.frame.size.height - frame.size.height;
        
        self.frame = frame;
    }];
    
    [self refresh];
    [self refreshFrame];
}

@end
